package org.pupil.router.impl;

import org.pupil.common.URL;
import org.pupil.router.LoadBalancer;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 负载均衡：轮询
 * @Author: pupil
 * @Date: 2024/07/16 下午 3:31
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    // 轮询id
    private static AtomicInteger roundRobinId = new AtomicInteger(0);


    @Override
    public URL select(List<URL> urls) {
        // 累加
        roundRobinId.addAndGet(1);
        // 判断id是否大于int类型最大值
        if (roundRobinId.get() == Integer.MAX_VALUE) {
            // 置零
            roundRobinId.set(0);
        }
        // 轮询获取服务并返回
        return urls.get(roundRobinId.get() % urls.size());
    }
}
